package com.internship.service;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.internship.util.StringUtil;

public class FileUpload {
	public static String  File(@RequestParam("file")MultipartFile file){
		 String result = "error";
         String filePath = "";
         if (file != null&&!file.isEmpty() ) {
       	  UUID uuid = UUID.randomUUID();
       	  filePath = getSession().getServletContext().getRealPath(
						"/")
						+ "upload" + "/" +uuid+file.getOriginalFilename().substring  
							    (file.getOriginalFilename().lastIndexOf(".")); 
             //取得当前上传文件的文件名称  
             String myFileName = file.getOriginalFilename();  
             //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
             if(!StringUtil.isEmpty(myFileName)){  
                 //定义上传路径  
                 File localFile = new File(filePath);  
                 try {
						file.transferTo(localFile);
						result = "upload" +"/"+uuid+file.getOriginalFilename().substring  
							    (file.getOriginalFilename().lastIndexOf("."));
					} catch (Exception e) {
						e.printStackTrace();
					}  
             }  
         }
		return result;  
	}
	
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}}
